﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Org.Eurekaa.DNJ.Ext.Common;
using Org.Eurekaa.DNJ.UI.WebControls;
using System.Web;
using Org.Eurekaa.DNJ.Helpers;

//TODO : Ajax upload (http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=512#start)
namespace Org.Eurekaa.DNJ.Ext.UI.WebControls
{
    public class MultiFileUpload : JQueryUIControl, IDNJPlugin
    {
        private FileUpload fUpload = new FileUpload();
        private Button btnUpload = new Button();
        public String UploadCaption { get; set; }
        public String StorePath { get; set; }


        public override void SaveSettings(ref object stateObject)
        {
            base.SaveSettings(ref stateObject);
            PageHelper.RegisterDNJResource("multifile", this.Page.Header);

        }
        public override void LoadSettings(object stateObject)
        {
            base.LoadSettings(stateObject);
        }

        protected override void CreateChildControls()
        {
            Controls.Clear();
            btnUpload.Click += new EventHandler(btnUpload_Click);
            fUpload.CssClass += " multi";

            if (!DesignMode)
            {
                Org.Eurekaa.DNJ.Config.ResourcesConfig.AddResource("multifile", "Org.Eurekaa.DNJ.Ext.PluginsData.FileUpload.jquery.MultiFile.js");                
            }
            if (String.IsNullOrEmpty(UploadCaption)) UploadCaption = "Upload";
            btnUpload.Text = UploadCaption;

            Controls.Add(fUpload);
            Controls.Add(btnUpload);
        }


        protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                // Get the HttpFileCollection
                HttpFileCollection hfc = Page.Request.Files;
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        hpf.SaveAs(StorePath + "\\" +
                          System.IO.Path.GetFileName(hpf.FileName));
                        //Page.Response.Write("<b>File: </b>" + hpf.FileName + " <b>Size:</b> " +
                          //  hpf.ContentLength + " <b>Type:</b> " + hpf.ContentType + " Uploaded Successfully <br/>");
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
        #region IDNJPlugin Members

        public string Version()
        {
            return "jQuery Multiple File Upload Plugin v1.46 - 2009-05-12";
        }

        public bool Embedded()
        {
            return true;
        }

        #endregion
    }
}
